﻿@page "/devicelog"
@using JT808Gateway.Core
@using System.Threading

<div class="row">
    <div class="col-4 col-sm-4">
        <span>选择设备:</span>
        <Select TValue="string" Items="Devices" ShowSearch="true" AutoClearSearchText="true" OnSelectedItemChanged="@((e)=>{ 
                    SelectedDevice = e;
                    if(!TabSet.Items.Any(x=>x.Text == $"Log-{e.Text}"))
                       TabSet.AddTab($"/consolelog/{e.Text}",$"Log-{e.Text}");
                    return Task.CompletedTask;
                })"></Select>
     </div>
     <div class="col-12 col-sm-12" style="margin-top:10px">
     <Tab IsCard @ref="TabSet" ShowClose="true">
     </Tab>
    </div>
</div>

@code {
    private List<SelectedItem> Devices { get; set; }

    private SelectedItem SelectedDevice { get; set; }

    private Tab TabSet { get; set; }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        Devices = new List<SelectedItem>();

        if (firstRender)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    RefreshDevices();

                    InvokeAsync(() =>
                    {
                        //定时刷新
                        StateHasChanged();
                    });

                    Thread.Sleep(5 * 1000);
                }
            });
        }

        return base.OnAfterRenderAsync(firstRender);
    }

    private void RefreshDevices()
    {
        Devices.Clear();

        foreach (var session in SessionManager.Instance.SessionList)
        {
            var p= (JT808Protocol.Models.JT808Package)session.DataContext;
            if (p == null) continue;

            var item = new SelectedItem
                {
                    Text = p.Header.SimNumber,
                    Value = p.Header.SimNumber
                };

            Devices.Add(item);
        }
    }
}
